package com.demo.project_template.base.pay.wxpay.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.demo.project_template.base.pay.wxpay.common.WechatJSAPIGetMsgUrlConstants;
import com.demo.project_template.base.pay.wxpay.entity.WxPayEntity;
import com.demo.project_template.base.pay.wxpay.service.WechatJSAPIGetMsgService;
import com.demo.project_template.base.pay.wxpay.util.WxLoginUtil;
import com.demo.project_template.base.pay.wxpay.vo.DecryptWeChartMsgVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import static com.demo.project_template.base.pay.wxpay.service.impl.WechatH5GetMsgServiceImpl.getDecryptWeChartMsgVO;

/**
 * @Author ZhangKeChen
 * @Date 2022/11/3
 * @Description
 */
@Slf4j
@Service
@Transactional
public class WechatJSAPIGetMsgServiceImpl implements WechatJSAPIGetMsgService {

    @Resource
    WxPayEntity wxPayEntity;

    /**
     * @param code 小程序微信获取openid的code
     * @return
     */
    @Override
    public DecryptWeChartMsgVO decryptWeChatOpenIdMsg(String code) {
        //用code获取openid请求地址
        String baseAccessTokenUrl = String.format(WechatJSAPIGetMsgUrlConstants.GetOpenIdByCode, wxPayEntity.weChatPayJSAPIAppId, wxPayEntity.weChatPayJSAPIApiV3Key, code);
        JSONObject userInfo = WxLoginUtil.getUserInFor(baseAccessTokenUrl);
        log.info("用户信息：{}", userInfo);
        DecryptWeChartMsgVO decryptWeChartMsgVo = new DecryptWeChartMsgVO();
        decryptWeChartMsgVo.setOpenId(userInfo.getString("openid"));
        return decryptWeChartMsgVo;
    }

    /**
     * @param code 小程序微信获取phone的code
     * @return
     */
    @Override
    public DecryptWeChartMsgVO decryptWeChatPhoneMsg(String code) {
        //用appid和secret获取access_token请求地址
        String getTokenUrl = String.format(WechatJSAPIGetMsgUrlConstants.GetAccessTokenByCode, wxPayEntity.weChatPayJSAPIAppId, wxPayEntity.weChatPayJSAPIApiV3Key);
        JSONObject userInfo = WxLoginUtil.getUserInFor(getTokenUrl);
        String accessToken = userInfo.getString("access_token");
        //使用access_token获取手机号码
        String phoneUrl = String.format(WechatJSAPIGetMsgUrlConstants.GetPhoneByAccessToken, accessToken);
        return getDecryptWeChartMsgVO(code, phoneUrl, log);
    }
}
